import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import { saveVisitedRoutes } from '@/utils'
import 'nprogress/nprogress.css'
import { useCurrentUsersStore } from '@/stores'

NProgress.configure({ showSpinner: false })


const routes = [
  {
    name: 'Home',
    path: '/',
    redirect: { name: 'Welcome' },
    component: () => import('../views/Home.vue'),
    children: [
      {
        name: 'Welcome',
        path: 'welcome',
        meta: {
          title: 'Welcome'
        },
        component: () => import('../views/Welcome.vue'),
      },
    ]
  },
  {
    name: 'Login',
    path: '/login',
    // redirect: { name: 'Home' },
    component: () => import('../views/Login.vue'),
  },
]

const router = createRouter({
  // 创建一个路由历史记录对象
  history: createWebHistory(),
  // 定义路由配置
  routes,
  // 启用严格模式，确保路由的唯一性和正确性
  strict: true,
  // 定义滚动行为，每次导航时滚动到页面顶部
  scrollBehavior: () => ({ left: 0, top: 0 })
})

router.beforeResolve(async (to) => {
  // 如果目标路由是登录页，直接放行
  if (to.name === 'Login') return;

  // 如果用户未登录，重定向到登录页
  if (!useCurrentUsersStore().currentUsers) {
    return { name: 'Login' };
  }
});

router.beforeEach((_, __, next) => {
  NProgress.start()
  next()
})

router.afterEach(async (to) => {
  const str = ['Login']
  if (!str.includes(to.name as string)) {
    await saveVisitedRoutes({ name: to.name, path: to.path, title: to.meta.title })
  }
  NProgress.done()
})

export default router